<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible" size="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="15">
          <el-row>
<!--            <el-col :span="22">-->
<!--              <el-form-item label="机构名称" prop="orgName">-->
<!--                <el-input v-model="formData.orgName" placeholder="请输入机构名称" />-->
<!--              </el-form-item>-->
<!--            </el-col>-->

            <el-col :span="22">
              <el-form-item label="所属科室" prop="departmentId">
                <el-tree-select
                  v-model="formData.departmentId"
                  :data="deptTree"
                  :default-expanded-keys="[0]"
                  :props="defaultProps"
                  check-strictly
                  node-key="id"
                  v-on:change="selectTree"
                />
              </el-form-item>
            </el-col>
<!--            <el-col :span="22">-->
<!--              <el-form-item label="科室名称" prop="departmentName">-->
<!--                <el-input v-model="formData.departmentName" placeholder="请输入科室名称" />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="22">
              <el-form-item label="医生姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入医生姓名" />
              </el-form-item>
            </el-col>
<!--            <el-col :span="22">-->
<!--              <el-form-item label="昵称" prop="nickname">-->
<!--                <el-input v-model="formData.nickname" placeholder="请输入昵称" />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="22">
              <el-form-item label="工作时段" prop="workRange">
                <el-input v-model="formData.workRange" placeholder="请输入工作时段" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="擅长病种" prop="tags">
                <el-input v-model="formData.tags" placeholder="请输入擅长病种" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="坐诊地址" prop="address">
                <el-input v-model="formData.address" placeholder="请输入坐诊地址" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="his医生编码" prop="hisDoctorCode">
                <el-input v-model="formData.hisDoctorCode" placeholder="请输入his医生编码" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="his医生名称" prop="hisDoctorName">
                <el-input v-model="formData.hisDoctorName" placeholder="请输入his医生名称" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="链接地址" prop="linkUrl">
                <el-input v-model="formData.linkUrl" placeholder="请输入链接地址" />
              </el-form-item>
            </el-col>

            <el-col :span="22">
              <el-form-item label="提示" prop="tips">
                <el-input type="textarea" v-model="formData.tips" :rows="2" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="通知" prop="notice">
                <el-input type="textarea" v-model="formData.notice" :rows="2" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="描述" prop="description">
                <el-input type="textarea" v-model="formData.description" :rows="2" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="formData.remark" :rows="2" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="图集" prop="pictures">
                <UploadImgs v-model="formData.pictures" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="附件" prop="files">
                <UploadFile v-model="formData.files" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="9">
          <el-row>
            <el-col :span="22">
              <el-form-item label="性别" prop="gender">
                <el-input v-model="formData.gender" placeholder="请输入性别" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="出生年月" prop="birthday">
                <el-input v-model="formData.birthday" placeholder="请输入出生年月" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="电话" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入电话" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="职称" prop="jobTitle">
                <el-input v-model="formData.jobTitle" placeholder="请输入职称" />
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="是否专家" prop="specialist">
                <template #label>
                  <Tooltip message="如果是专家，请选择开启" title="是否专家" />
                </template>
                <el-radio-group v-model="formData.specialist">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="有效状态" prop="status">
                <template #label>
                  <Tooltip message="开启后内容有效" title="有效状态" />
                </template>
                <el-radio-group v-model="formData.status">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="发布状态" prop="publish">
                <template #label>
                  <Tooltip message="开启后前端展示内容" title="发布状态" />
                </template>
                <el-radio-group v-model="formData.publish">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="置顶状态" prop="topping">
                <template #label>
                  <Tooltip message="开启后可展示在首页banner" title="置顶状态" />
                </template>
                <el-radio-group v-model="formData.topping">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="22" >
              <el-form-item :label-width="120" label="推荐状态" prop="recommend">
                <template #label>
                  <Tooltip message="开启后可展示在热门推荐" title="推荐状态" />
                </template>
                <el-radio-group v-model="formData.recommend">
                  <el-radio
                    v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
                    :key="dict.value"
                    :label="dict.value"
                  >
                    {{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="显示排序" prop="sort">
                <el-input-number v-model="formData.sort" :min="0" clearable controls-position="right" />
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="头像">
                <UploadImg v-model="formData.headImageUrl" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-form-item label="内容" prop="content">
            <Editor v-model="formData.content" height="250px" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { DoctorApi, DoctorVO } from '@/api/cms/doctor'
import { DepartmentApi, DepartmentVO } from '@/api/cms/department'
import { DICT_TYPE, getStrDictOptions, getDictOptions, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'

/** 医生信息 表单 */
defineOptions({ name: 'DoctorForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  nickname: undefined,
  gender: undefined,
  birthday: undefined,
  headImageUrl: undefined,
  phone: undefined,
  jobTitle: undefined,
  specialist: undefined,
  workRange: undefined,
  tags: undefined,
  address: undefined,
  orgName: undefined,
  departmentId: undefined,
  departmentName: undefined,
  hisDeptCode: undefined,
  hisDeptName: undefined,
  hisDoctorCode: undefined,
  hisDoctorName: undefined,
  linkUrl: undefined,
  tips: undefined,
  notice: undefined,
  description: undefined,
  content: undefined,
  contentFormat: undefined,
  remark: undefined,
  pictures: undefined,
  files: undefined,
  views: undefined,
  publishTime: undefined,
  publish: Number(1),
  topping: Number(1),
  recommend: Number(1),
  status: Number(1),
  sort: Number(0)
})
const formRules = reactive({
  departmentId: [{ required: true, message: '所属科室不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  departmentName: [{ required: true, message: '科室名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '有效状态不能为空', trigger: 'blur' }],
  publish: [{ required: true, message: '发布状态不能为空', trigger: 'blur' }],
  topping: [{ required: true, message: '置顶状态不能为空', trigger: 'blur' }],
  recommend: [{ required: true, message: '推荐状态不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '顺序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DoctorApi.getDoctor(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得列表
  await getTree()
  setForm(formData.value.departmentId)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DoctorVO
    if (formType.value === 'create') {
      await DoctorApi.createDoctor(data)
      message.success(t('common.createSuccess'))
    } else {
      await DoctorApi.updateDoctor(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}


/** 获取下拉框[科室]的数据  */
const queryParams = reactive({
  status: CommonStatusEnum.ENABLE
})

const deptList = ref<DepartmentVO[]>([]) // 列表的数据
const deptTree = ref<Tree[]>([]) // 树形结构
const getTree = async () => {
  deptTree.value = []
  const res = await DepartmentApi.getDepartmentList(queryParams)
  deptList.value = res
  deptTree.value = handleTree(res)
}

const setForm = async (departmentId: number) => {
  const find = deptList.value.find((item) => item.id == departmentId)
  console.table(find)
  if(find){
    formData.value.workRange = formData.value.workRange || find.workRange
    formData.value.address = formData.value.address || find.address
    formData.value.phone = formData.value.phone || find.phone
    formData.value.hisDeptCode = formData.value.hisDeptCode || find.hisDeptCode
    formData.value.hisDeptName = formData.value.hisDeptName || find.hisDeptName
  }
}

const selectTree = async (e:any) => {
  const find = deptList.value.find((item) => item.id == e)
  console.table(find)
  if(find){
    formData.value.workRange = formData.value.workRange || find.workRange
    formData.value.address = formData.value.address || find.address
    formData.value.phone = formData.value.phone || find.phone
    formData.value.hisDeptCode = find.hisDeptCode
    formData.value.hisDeptName = find.hisDeptName
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    nickname: undefined,
    gender: undefined,
    birthday: undefined,
    headImageUrl: undefined,
    phone: undefined,
    jobTitle: undefined,
    specialist: undefined,
    workRange: undefined,
    tags: undefined,
    address: undefined,
    orgName: undefined,
    departmentId: undefined,
    departmentName: undefined,
    hisDeptCode: undefined,
    hisDeptName: undefined,
    hisDoctorCode: undefined,
    hisDoctorName: undefined,
    linkUrl: undefined,
    tips: undefined,
    notice: undefined,
    description: undefined,
    content: undefined,
    contentFormat: undefined,
    remark: undefined,
    pictures: undefined,
    files: undefined,
    views: undefined,
    publishTime: undefined,
    publish: Number(1),
    topping: Number(1),
    status: Number(1),
    recommend: Number(1),
    sort: Number(0)
  }
  formRef.value?.resetFields()
}
</script>
